package com.sure.minion.web.interceptor;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sure.minion.services.base.handler.exception.BizAutoHandledException;

/**
 * 授权处理拦截器，在执行controller之前判断权限
 * 
 * @author huangjian
 * @date 2015-04-13
 */
@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			// 方法上是否有授权注解
			Authorization authorization = handlerMethod.getMethodAnnotation(Authorization.class);
			if (authorization == null) {
				// 方法所属类上是否有授权注解
				authorization = handlerMethod.getMethod().getDeclaringClass()
						.getAnnotation(Authorization.class);
				if (authorization == null) {
					// 无授权注解，禁止访问
					throw new BizAutoHandledException("COMMON_AUTHORITY_INVALIDATE");
				}
			}

			// 获取授权信息
			ArrayList<UserRole> roles = new ArrayList<UserRole>();
			for (int i = 0; i < authorization.value().length; i++) {
				roles.add(authorization.value()[i]);
			}

			// 判断是否可匿名访问
			if (roles.contains(UserRole.ANONYMOUS)) {
				return true;
			} else {
				// TODO 登录用户是否符合操作权限要求，不符合权限要求时，抛出异常
				// throw new GenericException("EC_AUTH_FAILED");
			}
		}
		return true;
	}
}
